<template>
    <div class="containe-home">
        <!-- 头部选择通道 -->
        <div class="header">
            <div>
                <span>当前车场：</span>
                <el-select v-model="parkId" placeholder="选择车场" class="select-park" @change="selectPark">
                    <el-option v-for="item in parkOptList" :key="item.parkingLotId" :label="item.parkingLotName" :value="item.parkingLotId">
                    </el-option>
                </el-select>
            </div>
            <div class="park-place">空余车位：{{ parkPlaceInfo.emptyPlaces }}/{{ parkPlaceInfo.totalPlaces }}</div>
        </div>
        <!-- 主要内容 -->
        <div class="content">
            <div class="content-left">
                <!-- 左侧内容 -->
                <!-- 入离场图片 -->
                <div class="park-img-info">
                    <div class="park-img-box">
                        <div class="title">
                            <el-select v-model="entryId" placeholder="入场通道" @change="selectDriveway('entryWs')" class="select-driveway">
                                <el-option
                                    v-for="item in channalEntryList"
                                    :key="item.drivewayId"
                                    :label="item.drivewayName"
                                    :value="item.drivewayId"
                                >
                                </el-option>
                            </el-select>
                        </div>
                        <div class="park-img">
                            <div v-if="inParkInfo.entCarImageUrl" class="real-img">
                                <img :src="inParkInfo.entCarImageUrl" />
                            </div>
                            <div v-else class="blank-img">
                                <img src="../assets/img/blank.png" class="blank" />
                                <span class="tips">暂无通道数据</span>
                            </div>
                        </div>
                    </div>
                    <div class="park-img-box">
                        <div class="title">
                            <el-select v-model="exitId" placeholder="出场通道" @change="selectDriveway('exitWs')" class="select-driveway">
                                <el-option
                                    v-for="item in channalExitList"
                                    :key="item.drivewayId"
                                    :label="item.drivewayName"
                                    :value="item.drivewayId"
                                >
                                </el-option>
                            </el-select>
                        </div>
                        <div class="park-img">
                            <div v-if="outParkInfo.exitCarImageUrl" class="real-img">
                                <img :src="outParkInfo.exitCarImageUrl" />
                            </div>
                            <div v-else class="blank-img">
                                <img src="../assets/img/blank.png" class="blank" />
                                <span class="tips">暂无通道数据</span>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 停车记录 -->
                <div class="park-record">
                    <el-tabs v-model="pannalIndex">
                        <el-tab-pane>
                            <span slot="label"><i class="el-icon-document tabar-icon"></i>停车信息</span>
                            <el-row class="inpark-info" :gutter="40">
                                <el-col :span="9">
                                    <el-timeline>
                                        <el-timeline-item placement="top">
                                            <el-card>
                                                <h4>入口LED：{{ inParkInfo.ledShow || '-' }}</h4>
                                            </el-card>
                                        </el-timeline-item>
                                    </el-timeline>
                                </el-col>
                                <el-col>
                                    <div class="park-search">
                                        <!-- 车牌搜索 -->
                                        <el-input class="search-input" placeholder="请输入" v-model="parkSearchName">
                                            <el-button slot="prepend" icon="el-icon-search"></el-button>
                                        </el-input>
                                        <el-button type="primary" class="search-btn" @click="searchInParkList">查询</el-button>
                                        <el-button type="primary" class="search-btn" @click="manualEntry">手动入场</el-button>
                                    </div>
                                    <el-table ref="parkTable" :data="parkRecord" style="width: 100%" border>
                                        <el-table-column label="车牌号码" align="center">
                                            <template slot-scope="scope"
                                                ><a @click="handleExit(scope.row)">{{ scope.row.carLicense }}</a></template
                                            >
                                        </el-table-column>
                                        <el-table-column label="入场时间" align="center">
                                            <template slot-scope="scope">{{ scope.row.entTime }}</template>
                                        </el-table-column>
                                        <el-table-column label="入场通道" align="center">
                                            <template slot-scope="scope">{{ scope.row.entDrivewayName }}</template>
                                        </el-table-column>
                                        <el-table-column label="入场图片" align="center">
                                            <template slot-scope="scope">{{ scope.row.exitLicenseImageUrl || '-' }}</template>
                                        </el-table-column>
                                    </el-table>
                                    <div class="pagination-area">
                                        <el-pagination
                                            background
                                            @current-change="handleCurrentChange"
                                            layout="total, prev, pager, next"
                                            :current-page.sync="pageNum"
                                            :total="total"
                                        >
                                        </el-pagination>
                                    </div>
                                </el-col>
                            </el-row>
                            <!-- 停车记录列表 -->
                        </el-tab-pane>
                    </el-tabs>
                </div>
            </div>
            <div class="content-right">
                <!-- 右侧内容 -->
                <div class="park-detail">
                    <div class="carlincense-info">
                        <!-- 停车类型 -->
                        <div class="park-type" v-if="outParkInfo.parkingType">{{ parkTypeOpt[outParkInfo.parkingType] }}</div>
                        <div class="carlincense" v-if="outParkInfo.carLicense">{{ outParkInfo.carLicense }}</div>
                    </div>
                    <div class="pay-detail">
                        <div>入场时间：{{ outParkInfo.entTime || '-' }}</div>
                        <div>离场时间：{{ outParkInfo.exitTime || '-' }}</div>
                        <div>停车时长：{{ outParkInfo.parkingTime || '-' }}</div>
                        <div>优惠金额：¥ {{ outParkInfo.discountAmount || '0' }}</div>
                        <div>已付金额：¥ {{ outParkInfo.payAmount || '0' }}</div>
                        <div>车辆类型：{{ outParkInfo.carTypeName || '-' }}</div>
                    </div>
                    <div class="final-pay">
                        <div class="freeTag" v-if="outParkInfo.payStatus=='payStatus'">免费离场</div>
                        <div class="order-pay-price">
                            应付金额：<span>¥ {{ outParkInfo.amount || 0 }}</span>
                        </div>
                        <div class="final-pay-price">
                            待支付：<span class="symble">¥</span><span class="money">{{ outParkInfo.payableAmount || 0 }}</span>
                        </div>
                    </div>
                </div>
                <!-- 操作按钮 -->
                <div class="park-handle">
                    <el-button type="primary">扫码收费</el-button>
                    <el-button type="primary" @click="payAction('CASH')">现金收费</el-button>
                    <el-button type="primary" @click="payAction('FREE')">免费放行</el-button>
                </div>
            </div>
        </div>
        <!-- 手动入场弹框 -->
        <el-dialog title="手动入场" :visible.sync="dialogFormVisible" width="500px" @close="closeModal">
            <el-form ref="modalForm" :rules="modalRules" :model="modalForm" label-width="120px" class="park-info">
                <!-- 车场信息配置 -->
                <el-form-item label="车牌号码：" prop="carLicense">
                    <el-input maxlength="8" v-model="modalForm.carLicense" autocomplete="off" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="入场时间：" prop="captureTime">
                    <el-date-picker
                        type="datetime"
                        placeholder="选择日期"
                        v-model="modalForm.captureTime"
                        style="width: 100%"
                        value-format="yyyy-MM-dd HH:mm:ss"
                    ></el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleSubmit">保 存</el-button>
                <el-button @click="dialogFormVisible = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getParkList, getDrivewayList, carEventEntry, getParkPlace, getInParkingPage, personneCarExit,cashFree } from '@/api/home';
import {webSocketUrl} from "@/utils/tools";
export default {
    name: 'Home', // 首页
    data() {
        return {
            parkId: '', //当前的车场
            entryId: '',
            exitId: '',
            parkOptList: [], //当前车场
            channalEntryList: [],
            channalExitList: [],
            pannalIndex: 0,
            parkRecord: [], //停车记录列表
            parkSearchName: '',
            inParkInfo: {}, //在场信息
            outParkInfo: {}, //离场信息
            entryWs: null,
            exitWs: null,
            parkTypeOpt: {
                WHITELIST: '白名单',
                MONTHLY: '月租',
                TEMP: '临停',
                EMPLOYEE: '员工停车',
                ARMY_POLICE_CAR: '军警车'
            },
            modalRules: {
                captureTime: [{ required: true, message: '该项为必填项' }],
                carLicense: [{ required: true, message: '该项为必填项' }]
            },
            modalForm: {
                captureTime: '',
                carLicense: ''
            },
            dialogFormVisible: false,
            parkPlaceInfo: {},
            total: 0,
            pageNum: 1
        };
    },
    components: {},
    created() {
        // 打开页面时获取当前车场下来列表;
        this.getParkListFun();
    },
    methods: {
        async payAction(payChannel){
            if(!this.outParkInfo.recordId){
                this.$message.info('暂无可出场车辆');
                return
            }
            const result = await cashFree({
                recordId: this.outParkInfo.recordIdStr,
				payAmount: this.outParkInfo.payableAmount,
                payChannel,
                payScene:'SENTRY_BOX'
            });
            if(result.code == 200){
                 this.$message.success('操作成功');
                 this.outParkInfo = {};
                 this.getInParkList(this.parkId);
            }else{
                 this.$message.error(result.msg);
            }
        },
        handleExit(row) {
            // 给在场车操作离场;
            this.$confirm('此操作将车辆进行离场, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const result = await personneCarExit({
                    recordId: row.recordId,
                    drivewayId: this.exitId
                });
                if (result.code == 200) {
                    this.$message.success('操作成功');
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        handleCurrentChange(val) {
            // 切换分页
            this.getInParkList(this.parkId);
        },
        searchInParkList() {
            // 查询当前在场车
            this.getInParkList(this.parkId);
        },
        // 获取在场车列表;
        async getInParkList(parkId) {
            const result = await getInParkingPage({
                parkingLotId: parkId,
                carLicense: this.parkSearchName,
                pageSize: 5,
                pageNo: this.pageNum
            });
            if (result.code == 200) {
                this.parkRecord = result.data.records;
                this.total = Number(result.data.total);
            }
        },
        async handleSubmit() {
            // 提交人工入场;
            const { captureTime, carLicense } = this.modalForm;
            const params = {
                captureTime,
                carLicense,
                drivewayId: this.entryId
            };
            const result = await carEventEntry(params);
            if (result.code == 200) {
                this.$message.success(result.data.ledMsg);
                this.dialogFormVisible = false;
                this.getParkPlace(this.parkId); //刷新下剩余车位数
                this.getInParkList(this.parkId);//刷新在场车辆
            } else {
                this.$message.info(result.msg);
            }
        },
        manualEntry() {
            //展示人工入场弹框
            this.dialogFormVisible = true;
        },
        closeModal() {
            this.dialogFormVisible = false;
        },
        selectPark(e, item) {
            // 选择停车场时候获取新的通道
            this.getDrivewayList('ENTRANCE'); //获取通道列表
            this.getDrivewayList('EXIT'); //获取通道列表
            this.getParkPlace(e); //获取车位信息;
        },
        async getParkPlace(parkId) {
            const result = await getParkPlace({
                parkingLotId: parkId
            });
            if (result.code != 200) {
                this.$message.error(result.msg);
                return;
            }
            this.parkPlaceInfo = result.data;
        },
        async getParkListFun() {
            const result = await getParkList();
            this.parkOptList = result.data;
            if (result.data.length == 0) {
                return;
            }
            this.parkId = result.data[0].parkingLotId;
            this.getDrivewayList('ENTRANCE'); //获取通道列表
            this.getDrivewayList('EXIT'); //获取通道列表
            this.getParkPlace(this.parkId); //获取剩余车位数
            this.getInParkList(this.parkId); //获取在场车
        },
        async getDrivewayList(type) {
            const result = await getDrivewayList({
                parkingLotId: this.parkId,
                drivewayType: type
            });
            if (result.code != 200) {
                this.$message.error(result.msg);
                return;
            }
            const data = result.data;
            if (data.length == 0) {
                return;
            }
            if (type == 'ENTRANCE') {
                this.channalEntryList = data;
                this.entryId = data[0].drivewayId; //设置默认第一个
                this.createWebsocketFun(this.entryId, 'ENTRANCE'); //创建入口长连接
            } else {
                this.channalExitList = data;
                this.exitId = data[0].drivewayId; //设置默认第一个出口
                this.createWebsocketFun(this.exitId, 'EXIT'); //创建出口长连接
            }
        },
        createWebsocketFun(drivewayId, type) {
            const that = this;
            const target = type === 'ENTRANCE' ? 'entryWs' : 'exitWs';
            // 关闭旧连接并清理资源
            if (that[target]) {
                that[target].close();
            }
            // 创建新的websocket连接
            const ws = new WebSocket(`${webSocketUrl}ws/ts/${drivewayId}`);
            that[target] = ws;
            ws.onopen = function (e) {
                ws.send('ping'); //发送消息监听心跳
                console.log('【连接成功】' + new Date().toUTCString(), ws);
            };
            ws.onmessage = function (e) {
                console.log(e);

                // 格式化获取到的信息
                var data = JSON.parse(e.data);
                console.log(data)
                const { cmdType, body } = data;
                if (cmdType == 'IN_CAR') {
                    //入口消息
                    that.inParkInfo = body;
                    that.getParkPlace(that.parkId); //刷新下剩余车位数
                } else {
                    that.outParkInfo = body;
                }
            };
            ws.onerror = function (e) {
                // reconnect();
                ws.close();
                console.log('连接错误:即将重连。。。');
            };
            ws.onclose = function (e) {
                // reconnect();
                console.log(ws, '连接关闭!');
            };
        },
        selectDriveway(target) {
            this[target].close();
            if (target == 'entryWs') {
                this.createWebsocketFun(this.entryId, 'ENTRANCE');
            } else if (target == 'exitWs') {
                this.createWebsocketFun(this.exitId, 'EXIT');
            }
        }
    },

    beforeDestroy() {
        ['entryWs', 'exitWs'].forEach((target) => {
            if (this[target]) {
                this[target].close();
            }
        });
    }
};
</script>

<style scoped>
.containe-home {
    padding: 52px 0;
}
.header {
    width: 100%;
    height: 60px;
    background: #e4ecff;
    padding: 12px 32px 0;
    box-sizing: border-box;
    display: flex;
}
/* 主要内容的UI */
.content {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    padding: 0 22px;
    margin-top: 16px;
}
.content-left {
    width: 68%;
}
.content-right {
    width: 31%;
}
/* 入离场图片 */
.park-img-info {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
}
.park-img-box {
    width: 49.5%;
    background: #fff;
    border-radius: 12px;
}
.park-img-box .title {
    font-size: 16px;
    line-height: 23px;
    color: #242a37;
    padding: 10px;
}
.park-img {
    height: 282px;
    width: 100%;
    border-radius: 12px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
}
.real-img img {
    height: 282px;
    width: 100%;
    object-fit: cover;
}
.park-img .blank-img {
    display: flex;
    flex-direction: column;
    align-items: center;
}
.park-img .blank-img img {
    width: 108px;
    height: 57px;
    margin-bottom: 20px;
}
/* 停车记录 */
.park-record {
    margin-top: 10px;
    background: #fff;
    border-radius: 4px;
    min-height: 30px;
    padding: 15px 21px;
}
.tabar-icon {
    margin-right: 5px;
}
.inpark-info {
    display: flex;
}
/* 右侧停车详情和操作记录 */
.park-detail {
    padding: 20px 18px;
    background: #ffffff;
    border-radius: 4px;
    margin-bottom: 16px;
}
/* 车牌部分 */
.carlincense-info {
    margin-bottom: 14px;
}
.carlincense-info .carlincense {
    width: 161px;
    height: 52px;
    line-height: 52px;
    text-align: center;
    background: #2f7df1;
    border-radius: 5px;
    border: 1px solid #ffffff;
    font-size: 26px;
    color: #ffffff;
}
/* 费用部分 */
.pay-detail {
    font-size: 18px;
    color: #666a74;
    line-height: 30px;
}
.pay-detail > div {
    margin-bottom: 10px;
}
.final-pay {
    display: flex;
    justify-content: flex-end;
    align-items: baseline;
}
.freeTag{
    font-size: 18px;
    margin-right: 30px;
     color: #f24a45;
}
.order-pay-price {
    font-size: 14px;
    color: #a4a8b0;
    line-height: 19px;
    margin-right: 12px;
}
.order-pay-price span {
    text-decoration: line-through;
}
.final-pay-price {
    font-size: 14px;
    color: #666a74;
    line-height: 19px;
}
.final-pay-price .symble {
    font-size: 24px;
    color: #f24a45;
}
.final-pay-price .money {
    font-size: 40px;
    color: #f24a45;
}
/* 操作按钮 */
.park-handle {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.park-handle .el-button {
    width: 33%;
}
.select-park ::v-deep .el-input__inner {
    border-radius: 40px;
}
.select-driveway ::v-deep .el-input__inner {
    width: 207px;
    height: 32px;
    background: #edeef2;
    border-radius: 16px;
    border-color: #edeef2;
    color: #242a37;
}
.select-driveway ::v-deep .el-input__suffix {
    top: 5px;
}
.select-driveway ::v-deep .is-focus .el-input__suffix {
    top: -5px;
}
.park-search {
    display: flex;
    margin-bottom: 20px;
}
.search-input {
    width: 260px;
    margin-right: 20px;
}
.park-type {
    background-image: url(../assets/img/car_type.png);
    text-align: center;
    background-size: 87px 36px;
    /* background: #2d4fa2; */
    line-height: 30px;
    font-size: 16px;
    color: #ffc700;
    width: 87px;
    background-repeat: no-repeat;
}
.park-place {
    line-height: 40px;
    margin-left: 35px;
}
</style>
